﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace zjxj_repair.Utils
{
    public static class BarcodeScannerServer
    {
        public static void BarcodeServer(string ip, int port)
        {
            // 设置TCP监听端口
            TcpListener listener = new TcpListener(IPAddress.Parse(ip), port);

            try
            {
                listener.Start();

                // 持续监听连接
                while (true)
                {
                    // 等待扫码枪连接
                    TcpClient client = listener.AcceptTcpClient();

                    // 启动一个新线程处理扫码枪发送的数据
                    Thread clientThread = new Thread(() => HandleClient(client));
                    clientThread.Start();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
        }

        // 处理扫码枪的数据
        static void HandleClient(TcpClient client)
        {
            try
            {
                // 获取客户端的网络流
                NetworkStream stream = client.GetStream();

                byte[] buffer = new byte[1024];

                int bytesRead;

                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    string scannedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);

                    scannedData.TrimEnd('\r');

                    Thread thread = new Thread(() =>
                    {
                        Clipboard.SetText(scannedData);
                    });

                    thread.SetApartmentState(ApartmentState.STA);

                    thread.Start();

                    thread.Join();

                    Console.WriteLine(scannedData);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理客户端时发生错误: {ex.Message}");
            }
            finally
            {
                // 关闭连接
                client.Close();
            }
        }
    }
}
